<template>
  <ul class="find_list" ref="findListRef" v-loading="flag">
    <li
      class="list_item"
      v-for="(item, index) in findList"
      :key="index"
      :ref="findListItemRef"
    >
      <img :src="item.url" alt="" @load="handleImgLoad(index)" />
      <h5>{{ item.type }}</h5>
    </li>
  </ul>
</template>

<script>
import {
  defineComponent,
  nextTick,
  onBeforeMount,
  onMounted,
  reactive,
  ref,
} from "vue";
import { getFindData } from "../api/pictures";
export default defineComponent({
  setup() {
    onMounted(() => {
      handleGetFind();
    });

    let flag = ref(true);

    let columnsHeightArr = [];

    let findList = ref(null);

    let findListRef = ref(null);

    // 存储dom数组
    const listItemArr = ref([]);

    let columns;

    // 动态获取间隔
    let grap;

    let findListItemRef = (el) => {
      listItemArr.value.push(el);
    };

    const handleGetFind = async () => {
      const { data: res } = await getFindData();
      if (res.code === 200) {
        findList.value = res.data;

        nextTick(() => {
          waterfallHandler();
          flag.value = false;
        });
      }
    };

    // 瀑布流处理
    const waterfallHandler = () => {
      // 容器宽度
      const clientWidth = findListRef.value.clientWidth;

      const itemWidth = 240;

      // 获取列数
      columns = Math.floor(clientWidth / itemWidth);

      grap = (clientWidth - itemWidth * columns) / (columns - 1);

      for (let i = 0; i < listItemArr.value.length; i++) {
        if (i < columns) {
          listItemArr.value[i].style.top = 0;
          if ((i + 1) % columns === 0) {
            listItemArr.value[i].style.right = 0;
          } else {
            listItemArr.value[i].style.left = (itemWidth + grap) * i + "px";
          }
        } else {
        }
      }
    };

    // 图片加载
    const handleImgLoad = (index) => {
      if (index < columns) {
        columnsHeightArr.push(listItemArr.value[index].offsetHeight);
      } else {
        let minHeight = Math.min(...columnsHeightArr);
        let minIndex = columnsHeightArr.indexOf(minHeight);
        console.log(minIndex);

        listItemArr.value[index].style.left =
          listItemArr.value[minIndex].offsetLeft + "px";
        listItemArr.value[index].style.top = minHeight + grap + "px";
        // 更新列高度
        columnsHeightArr[minIndex] =
          minHeight + listItemArr.value[index].offsetHeight + grap;
      }
    };

    return {
      flag,
      findList,
      findListRef,
      findListItemRef,
      handleImgLoad,
    };
  },
});
</script>
<style lang="scss" scoped>
.find_list {
  position: relative;
  margin-top: 20px;
}
.list_item {
  position: absolute;
  padding: 10px;
  width: 240px;
  box-sizing: border-box;
  border-radius: 4px;
  box-shadow: 2px 2px 3px #cccccc;
  background-color: #ffffff;
  transition: all 0.3s ease;
  img {
    width: 100%;
  }

  h5 {
    font-size: 14px;
  }
}
</style>